<template>
  <Dialog
    v-model="dialogVisible"
    width="60%"
    maxHeight="60vh"
    title="上传支付凭证"
    :before-close="() => closeDialog(formRef)"
  >
    <el-form :model="form" ref="formRef" :rules="rules as FormRules" label-width="120px">
      <div class="w-full flex flex-col">
        <el-form-item label="订单总金额">
          <el-input v-model="form.total_amount" disabled />
        </el-form-item>
        <el-form-item label="已支付金额">
          <el-input v-model="form.pay_amount" disabled />
        </el-form-item>
        <el-form-item label="未支付金额">
          <el-input v-model="form.unpay_amount" disabled />
        </el-form-item>
        <el-form-item label="费用类型" prop="fee_type">
          <el-select v-model="form.fee_type" placeholder="请选择费用类型">
            <el-option label="订单费用" :value="1" disabled />
            <el-option label="物流费用" :value="2" disabled />
          </el-select>
        </el-form-item>
        <el-form-item label="交易流水号" prop="voucher_code">
          <el-input v-model="form.voucher_code" />
        </el-form-item>
        <el-form-item label="支付金额" prop="paid_amount">
          <el-input-number
            class="!w-full"
            v-model="form.paid_amount"
            :min="0"
            :max="form.total_amount ? Number(form.total_amount) : 0"
          />
        </el-form-item>
        <el-form-item :label="t('order.orderUpload')" prop="att_path">
          <!-- <div class="flex flex-items-center"> -->
          <UploadFile
            url="/common/uploadFile"
            ref="UploadFileRef"
            class="w-100%"
            drag
            :file-type="['png', 'jpg', 'jpeg', 'bmp', 'pdf', 'word', 'txt']"
            :params="{ directory: 6 }"
            :limit="9"
            upload-file-button-name="点击上传或拖拽到此处上传"
            buttonWidth="100%"
            list-type="picture"
            :button-link="true"
            :show-file-list="true"
            @upload-success-res="handleUploadCallback"
            @handle-remove-file="handleRemoveFile"
            @handle-picture-card-preview="handlePictureCardPreview"
          />
          <!-- </div> -->
        </el-form-item>
      </div>
    </el-form>
    <template #footer>
      <el-button class="m-r-4" @click="closeDialog(formRef)"
        >{{ t('system.parameterConfig.cancel') }}
      </el-button>
      <el-button type="primary" @click="submit(formRef)">{{ t('common.ok') }} </el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { type FormInstance, type FormRules, ElMessage, ElMessageBox } from 'element-plus'
import { uploadPaymentApi } from '@/api/order/pay'
import UploadFile from '@/components/UploadFile/index.vue'
import { createImageViewer } from '@/components/ImageViewer'
const { push } = useRouter()

const { t } = useI18n()

const emits = defineEmits(['refresh'])
const dialogVisible = ref<boolean>(false)
const formRef = ref<FormInstance>()
const form = ref<Record<string, any>>({
  order_id: '',
  att_path: [],
  voucher_id: [],
  order_type: 'wholesal',
  voucher_code: '',
  paid_amount: 0,
  fee_type: 1
})

const rowDetail = ref<Record<string, any>>()

const rules = ref<FormRules>({
  voucher_code: [
    {
      required: true,
      message: t('common.inputText') + t('wholesalOrder.transactionNumber'),
      trigger: ['blur', 'change']
    }
  ],
  paid_amount: [
    {
      required: true,
      message: t('wholesalOrder.theAmountToBePaidMsg'),
      trigger: ['blur', 'change']
    }
  ],
  att_path: [
    {
      required: true,
      message: t('common.selectText') + t('wholesalOrder.proofOfPayment'),
      trigger: ['blur', 'change']
    }
  ]
})

//上传成功以后回调
const handleUploadCallback = (val: any) => {
  if (!val) return

  if (!form.value.att_path) {
    form.value.att_path = []
  }
  if (!form.value.voucher_id) {
    form.value.voucher_id = []
  }

  form.value.att_path.push(val)
  if (val.id) {
    form.value.voucher_id.push(val.id)
  }
}

const handleRemoveFile = (val: any) => {
  if (!val || !val.uid) return

  if (form.value.att_path && form.value.att_path.length) {
    form.value.att_path = form.value.att_path.filter(
      (item: Record<string, any>) => item?.uploadFile?.uid !== val.uid
    )
  }
  if (form.value.voucher_id && form.value.voucher_id.length) {
    form.value.voucher_id = form.value.voucher_id.filter(
      (item: Record<string, any>) => item?.uploadFile?.uid !== val.uid
    )
  }
}

const handlePictureCardPreview = (val: any) => {
  if (!val) return
  createImageViewer({
    urlList: [val],
    zIndex: 3000
  })
}

const submit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      ElMessageBox.confirm('支付凭证确认之后无法修改，请谨慎操作', t('purchase.logistics.tips'), {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const resp = await uploadPaymentApi({
            order_id: form.value.order_id,
            voucher_id: form.value.voucher_id,
            order_type: form.value.order_type,
            voucher_code: form.value.voucher_code,
            paid_amount: form.value.paid_amount,
            fee_type: form.value.fee_type
          })
          if (resp.code === 0) {
            ElMessage.success(t('order.uploadSucMsg'))
            closeDialog(formEl)
            emits('refresh')
            // push({
            //   path: `/order/wholesal-order-management/detail`,
            //   query: { id: rowDetail.value?.id }
            // })
          }
        })
        .catch(() => {})
    }
  })
}

const closeDialog = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  form.value = {
    order_id: '',
    att_path: [],
    voucher_id: [],
    order_type: 'wholesal',
    voucher_code: '',
    paid_amount: 0,
    total_amount: '',
    pay_amount: '',
    unpay_amount: '',
    fee_type: 1
  }
  formEl.resetFields()
  dialogVisible.value = false
}

const getBackShow = async (row: Record<string, any>) => {
  form.value.order_id = row.id
  form.value.pay_amount = row.pay_amount
  form.value.total_amount = row.total_amount
  form.value.unpay_amount = (Number(row.total_amount) - Number(row.pay_amount)).toFixed(2)
  rowDetail.value = row
}

defineExpose({
  dialogVisible,
  getBackShow
})
</script>
<style lang="less" scoped></style>
